<template>
    <div style="width: 50%; margin: 5px auto;">
        <div class="card" style="margin-bottom: 100px;">
            <div style="font-weight: bold; font-size: 24px; margin-bottom: 50px;">发表新博客/编辑博客</div>
          <div class="blog-post-form">
            <h1>发表新博客/编辑博客</h1>
            <el-form :model="form" label-position="top" :rules="rules" ref="blogForm">
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="标题"></el-input>
              </el-form-item>

              <el-form-item label="封面">
                <el-upload
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload">
                  <el-button type="primary" plain>上传封面</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </el-form-item>

              <el-form-item label="分类" prop="category">
                <el-select v-model="form.category" placeholder="请选择">
                  <el-option
                      v-for="item in categories"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="标签" prop="tags">
                <el-select v-model="form.tags" multiple placeholder="请选择">
                  <el-option
                      v-for="item in tags"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="内容" prop="content">
                <el-input
                    type="textarea"
                    :rows="10"
                    placeholder="请输入内容"
                    v-model="form.content">
                </el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="submitForm('blogForm')">发布</el-button>
                <el-button @click="resetForm('blogForm')">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
    </div>
</template>
<script>
import axios from "axios";

export default {
  data() {
    return {
      form: {
        title: '',
        description: '',
        cover: '',
        category: '',
        tags: [],
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      categories: [
        { value: 'technology', label: '技术' },
        { value: 'lifestyle', label: '生活' },
        { value: 'travel', label: '旅行' }
      ],
      tags: [
        { value: 'vue', label: 'Vue.js' },
        { value: 'react', label: 'React' },
        { value: 'nodejs', label: 'Node.js' },
        { value: 'python', label: 'Python' }
      ]
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log('submit!', this.form);
          // Here you would typically send the form data to your backend
          this.loading = true;
          axios.post('api/user/create-post', this.form, { headers: { token: this.token } })
              .then(() => {
                this.$message.success('博客发布成功！');
                this.resetForm(formName);
              })
              .catch(error => {
                this.$message.error('发布失败：' + (error.response?.data?.message || '未知错误'));
              })
              .finally(() => {
                this.loading = false;
              });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.form.cover = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 0.5;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 500KB!');
      }
      return isJPG && isLt2M;
    }
  },
  created() {
    this.token = localStorage.getItem("token");
    if (!this.token) {
      this.$router.push("/login");
    } else {
      this.getData();
      this.load();
    }
  },
};
</script>

<style scoped>

</style>